import axios from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import type { Result } from '@/types/api'

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    console.log('发送请求:', {
      url: config.url,
      method: config.method,
      headers: config.headers,
      params: config.params,
      data: config.data
    })
    const token = localStorage.getItem('admin-token')
    if (token) {
      config.headers = config.headers || {}
      config.headers['admin-token'] = token
    }
    return config
  },
  (error) => {
    console.error('请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    console.log('收到响应:', {
      url: response.config.url,
      method: response.config.method,
      status: response.status,
      statusText: response.statusText,
      data: response.data
    })
    return response
  },
  (error) => {
    console.error('响应拦截器错误:', {
      config: error.config,
      response: error.response,
      message: error.message
    })
    const { status } = error.response || {}
    switch (status) {
      case 401:
        ElMessage.error('未登录或token已过期')
        break
      case 403:
        ElMessage.error('没有权限')
        break
      case 404:
        ElMessage.error('请求的资源不存在')
        break
      case 500:
        ElMessage.error('服务器错误')
        break
      default:
        ElMessage.error('网络错误')
    }
    return Promise.reject(error)
  }
)

// 重新导出axios方法，并添加正确的类型
interface Http {
  get<T = any>(url: string, config?: any): Promise<AxiosResponse<T>>
  post<T = any>(url: string, data?: any, config?: any): Promise<AxiosResponse<T>>
  put<T = any>(url: string, data?: any, config?: any): Promise<AxiosResponse<T>>
  delete<T = any>(url: string, config?: any): Promise<AxiosResponse<T>>
}

const http: Http = {
  get: (url, config) => service.get(url, config),
  post: (url, data, config) => service.post(url, data, config),
  put: (url, data, config) => service.put(url, data, config),
  delete: (url, config) => service.delete(url, config)
}

export default http